package com.azt.front.action.company;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.azt.api.dto.BranchCompanyManage;
import com.azt.api.dto.UserMsgDto;
import com.azt.api.enums.UserFuncShowTypeEnum;
import com.azt.api.enums.UserFuncTypeEnum;
import com.azt.api.pojo.Company;
import com.azt.api.pojo.Role;
import com.azt.api.pojo.User;
import com.azt.api.pojo.UserApplyCompany;
import com.azt.api.pojo.UserFunction;
import com.azt.api.pojo.UserRole;
import com.azt.api.service.CompanyService;
import com.azt.api.service.EnqEnquiryService;
import com.azt.api.service.EnqQuoteService;
import com.azt.api.service.FunctionService;
import com.azt.api.service.MsgConfigService;
import com.azt.api.service.UserPermissionService;
import com.azt.api.service.UserService;
import com.azt.front.permission.RequireCompany;
import com.azt.front.permission.RequirePermission;
import com.azt.front.permission.RequirePurchase;
import com.azt.front.permission.RequireUser;
import com.azt.front.utils.ContextUtil;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.CommonUtil;
import com.azt.utils.RequestUtils;

/** 
 * @ClassName: OrgStructureAction 
 * @Description: 左侧菜单组织架构控制器
 * @author: zhaheng
 * @date: 2016年10月8日 下午3:35:30  
 */
@Controller
@RequireCompany
@RequestMapping("/orgstruct")
public class OrgStructureAction {
	@Autowired
	private CompanyService companyservice;
	@Autowired
	private EnqEnquiryService enqEnquiryService;
	@Autowired
	private EnqQuoteService enqQuoteService;
	@Autowired
	private CompanyService companyService;
	@Autowired 
	UserPermissionService userPermissionService;
	@Autowired
	private UserService userService;
	@Autowired
	private MsgConfigService msgConfigService;
	@Autowired
	private FunctionService functionService; 
	

	
	/**分公司列表页面*/
	@RequireUser
	@RequestMapping("/listBranchCompany")
	@RequirePurchase
	@RequirePermission("branchManage")
	public String BranchCompany(Integer pageNo,HttpServletRequest request , HttpServletResponse response , Model model){
    		  Company company = ContextUtil.getCompany();
    		  if(company!=null){
    				//分公司搜索关键词
    					Map<String, String> searchMap=RequestUtils.getSearchMap(request);
        				String branchCompany = searchMap.get("so_branchCompany");
        				Pagination page=companyservice.searchBranchCompany(pageNo==null?1:pageNo, 8, company.getId(),searchMap);//8页
        				model.addAttribute("bckeyword", branchCompany);
        				model.addAttribute("pagination", page);
        				if(page==null || page.getList()==null || page.getList().size()==0){
        					return "orgstructure/fristAddBranch";
        				}
    		  }else{
    			  return "company/companySearch";
    		  }

		return "orgstructure/companyManage";
	}
	
	/**加载三级分公司数据**/
	@RequireUser
	@RequestMapping("/listSanCompany")
	@RequirePurchase
	@RequirePermission("branchManage")
	public String sanCompany(Integer branchCompanyId,int classIndex,HttpServletRequest request , HttpServletResponse response , Model model){
		List<BranchCompanyManage> sanCompany = companyService.selectBranchCompany(branchCompanyId,null);
		model.addAttribute("sanCompany", sanCompany);
		model.addAttribute("classIndex", classIndex);
		return "orgstructure/sanComapny";
	}
	
	/**删除分公司**/
	@RequireUser
	@ResponseBody
	@RequestMapping("/delBranchCompany")
	@RequirePurchase
	@RequirePermission("branchManage")
	public AjaxJson delBranchCompany(Integer branchCompanyId,HttpServletRequest request , HttpServletResponse response , Model model){
		if(branchCompanyId!=null){
			try {
				companyService.delBranchCompany(branchCompanyId);
			} catch (Exception e) {
				AjaxJson.error("删除失败");
			}
		}
		
		return AjaxJson.success();
	}
	
	
	/**首次新增分公司*/
	@RequireUser
	@RequestMapping("/fristBranchCompany")
	@RequirePurchase
	@RequirePermission("branchManage")
	public String firtsaddBranchCompany(HttpServletRequest request , HttpServletResponse response , Model model){
		//如果该公司下面没有分公司
    		  Company company = ContextUtil.getCompany();
    		  if(company!=null){
    			  List<Company> branchCompanys = companyservice.getBranchCompany(company.getId());
        		  if(branchCompanys!=null &&  branchCompanys.size()>0){
        			  return "redirect:/orgstruct/addBranchCompany";
        		  }else{
        			  return "orgstructure/fristAddBranch";
        		  }
    		  }
    		
    		  return "/company/info";//完善资料
    		  
	}
	
	/***添加分公司列表*/
	@RequireUser
	@RequestMapping("/addBranchCompany")
	@RequirePurchase
	@RequirePermission("branchManage")
	public  String addBranchCompany(Integer branchCompanyId,HttpServletRequest request , HttpServletResponse response , Model model){
		Company company = ContextUtil.getCompany();
		Role currentRole = ContextUtil.getCurrentRole();
		
		List<Company> branchCompanys = companyservice.getBranchCompany(company.getId());

		model.addAttribute("company",company);
	
		List<UserFunction> parentTree=functionService.findFuncByRoleId(currentRole.getId().intValue(),UserFuncTypeEnum.MENU.getValue(),UserFuncShowTypeEnum.LEFT.getValue());//根据当前的ROLEID拿到权限菜单
		
		List<UserFunction> branchTree =null;
		//查询所有的分公司列表，包括自己做为选项，张云天说的2016.10.15
		List<Company> allcompany=new ArrayList<Company>();
		allcompany.add(company);
		
		//如果是编辑，则查询分公司的所拥有权限
		if(branchCompanyId!=null){
			//取公司取用户取权限
			Company  branchcompany= companyservice.getCompanyById(branchCompanyId);
			//三级公司
			List<Company> sanBranchCompany = companyservice.allBranchCompany(branchCompanyId);
			//编辑进来不能已有自己   有三级的时候不能修改为其他二级
			List<Company> templist = new ArrayList<Company>();//临时删除集合
			if(branchCompanys!=null && branchCompanys.size()>0){
				for(Company brc:branchCompanys){
					if(brc.getId().equals(branchCompanyId)){
						templist.add(brc);
					}
				}
			}
			
			branchCompanys.removeAll(templist);
			//没有三级
			if(sanBranchCompany==null || sanBranchCompany.size()==0){
				allcompany.addAll(branchCompanys);
			}
				model.addAttribute("branchcompany",branchcompany);
			
			// 得到这个角色
			Map Parameter = new HashMap();
			Parameter.put("companyId", branchcompany.getId());
			Parameter.put("roleType", currentRole.getRoleType());
			Parameter.put("ifAdmin", 1); //管理员
			List<Role> roles = userPermissionService.getRoleByParameter(Parameter);
			List<User> userByAdminRole = userService.getUserByAdminRole(branchcompany.getId(), roles);
			//只有一个
			if(userByAdminRole!=null && userByAdminRole.size()==1){
				model.addAttribute("userAdmin",userByAdminRole.get(0));
			}
			//权限  只加载左侧菜单  
			
			if(roles!=null && roles.size()==1){
				
				branchTree	= functionService.findFuncByRoleId(roles.get(0).getId(), UserFuncTypeEnum.MENU.getValue(),UserFuncShowTypeEnum.LEFT.getValue());
		
			}
			model.addAttribute("branchcompany",branchcompany);
		}else{
			allcompany.addAll(branchCompanys);
		}
		model.addAttribute("allcompany",allcompany);
		List<UserFunction> markTree = functionService.markTree(parentTree,branchTree);
		
		model.addAttribute("loadMenuTree",markTree);
		
		return "orgstructure/addBranchCompany";
	}
	
	/**验证公司名和负责人*/
	@ResponseBody
	@RequestMapping("/validateNameOrMobile")
	public JSONObject validateRealNameMobile(Integer branchCompanyId,String mobile,String branchName){
		Company company = ContextUtil.getCompany();
		JSONObject json =new JSONObject();
		json.put("obj", 0);
		//公司名称放开
		if(StringUtils.isNotBlank(branchName)){
		 Boolean checkBranchCompany = companyservice.checkBranchCompanyName(branchName,company,branchCompanyId);
			if(!checkBranchCompany){
				//报错提示
				json.put("obj", 3);
				json.put("error", "该公司名称已存在！");
				return json;
			}
		}
		
		if(StringUtils.isNotBlank(mobile)){
			User  user= null;
			try{
				user= userService.getUserByMobile(mobile);//根据填写的手机号查
			} catch (Exception e){
				//数据有问题
				json.put("obj", 3);
				json.put("error","号码重复，该手机号不可使用。");
				return json;
			}
			if(user!=null){
				String hiddenrealName =user.getRealName()!=null?"*"+user.getRealName().substring(1).toString():"";
				String realNameTip =user.getRealName()!=null?"*"+user.getRealName().substring(1)+"，可以继续添加。":mobile.substring(0, 3)+"****"+mobile.substring(7)+"，可以继续添加。";
				json.put("realName", user.getRealName());
				json.put("hiddenrealName", hiddenrealName);
				//未绑定公司
				if(user.getCompanyId()==null){
					json.put("obj", 1);//分公司负责人平台注册过，未绑定公司
					json.put("ok", realNameTip);
					return json;
				}
				
				if(branchCompanyId!=null){//编辑
					if(!user.getCompanyId().equals(branchCompanyId)){
						//报错提示
						json.put("obj", 3);
						json.put("error","该手机号已经绑定过其他企业，请更换其他号码。");
						return json;
					}else{
						json.put("ok", realNameTip);
					}
				}else{//新增
					if(user.getCompanyId()!=null){
						//报错提示
						json.put("obj", 3);
						json.put("error","该手机号已经绑定过其他企业，请更换其他号码。");
						return json;
					}else{
						json.put("ok", realNameTip);
					}
				}
				
			}else{
				//ok 只要不设置error都ok
				json.put("obj", 2);//分公司负责人未在平台注册过
				return json;
			}
		}
		
		return json;
	}
	
	
	/**新增保存或编辑分公司*/
	@ResponseBody
	@RequestMapping("/saveBranchCompany")
	@RequirePurchase
	@RequirePermission("branchManage")
	public AjaxJson saveBrqanchCompany(HttpServletRequest request , HttpServletResponse response ,Model model){
		Company company = ContextUtil.getCompany();
		Role currentRole = ContextUtil.getCurrentRole();
		String data=request.getParameter("data");
		if(StringUtils.isNotBlank(data)){
			try {
				Map<String,Object> parseMap = JSON.parseObject(data, Map.class);
				String branchCompanyName = (String) parseMap.get("branchCompanyName");
				String mobile = (String) parseMap.get("mobile1");
				String oldmobile = (String) parseMap.get("oldmobile");
				parseMap.put("RoleType", currentRole.getRoleType());
				
				Integer branchCompanyId=null;
				if(parseMap.get("branchCompanyId")!=null && StringUtils.isNotBlank(parseMap.get("branchCompanyId").toString())){
					branchCompanyId=Integer.parseInt(parseMap.get("branchCompanyId").toString());
				}
				
				Map<String, String> params = new HashMap();
				params.put("company", company.getCompanyName());
				params.put("branchcompany",branchCompanyName);	
				/**发送短信*/
				JSONObject validatejson = validateRealNameMobile(branchCompanyId,mobile,branchCompanyName);
				Integer obj=(Integer) validatejson.get("obj");
					String code=null;
					if(obj!=3){
						int success=companyService.saveOrUpdateBranchCompany(company, parseMap,branchCompanyId);
						if(success==2){
							return AjaxJson.error("保存失败，请稍后再试。");
						}else if(success==0){
							return AjaxJson.error("数据错误，保存失败。");
						}
					}
					
					if(obj==1){//未绑定公司
						code = "REGISTERED_COMPANY";
					}
					
					if(obj==2){//未在平台注册
						params.put("username",mobile);
						params.put("password",CommonUtil.DEFUALT_USER_PASSWORD);
						code = "UNBIND_COMPANY";
					}
					
					//编辑时未换手机号，不提示
					if(branchCompanyId!=null){
						if(oldmobile!=null && oldmobile.equals(mobile)){
							code=null;
						}
					}
					
					//发送短信
					if(StringUtils.isNotBlank(code)){
						List users=new ArrayList();
						UserMsgDto umd=new UserMsgDto();
						umd.setMobile(mobile);
						users.add(umd);
						msgConfigService.sendMessage(code, params, null, users);
					}
				
			} catch (Exception e) {
				e.printStackTrace();
				return AjaxJson.error("分公司资料保存失败。");
			}
	
		}else{
			return AjaxJson.error("抱歉，数据不能空！");
		}
		
		return AjaxJson.success();
	}
	
	
	/**查看项目*/
	@RequireUser
	@RequestMapping("/showItems")
	@RequirePurchase
	@RequirePermission("branchManage")
	public String showCompanyItem(Integer pageNo,Integer branchCompanyId,HttpServletRequest request , HttpServletResponse response , Model model){
		Map<String, String> searchMap=RequestUtils.getSearchMap(request);
		String keyword = searchMap.get("so_keyword");
		String sdate = searchMap.get("so_sdate");
		String endate = searchMap.get("so_endate");
		
		if(branchCompanyId!=null){
			searchMap.put("branchCompanyId", branchCompanyId.toString());//放入参数到分页
			Pagination  page = enqEnquiryService.getEnqProjectItemByCompanyId(pageNo==null?1:pageNo, 8, branchCompanyId,searchMap);
			model.addAttribute("branchCompanyId", branchCompanyId);
			model.addAttribute("pagination", page);
		}
		model.addAttribute("keyword", keyword);
		model.addAttribute("sdatetime", sdate);
		model.addAttribute("endatetime", endate);
		
		return "orgstructure/companyItems";
	}
	
	/**报价详情**/
	@RequireUser
	@RequestMapping("/loadQuoteModel")
	@RequirePurchase
	@RequirePermission("branchManage")
	public String loadQuoteModel(Integer pageNo,Integer projectId,HttpServletRequest request, HttpServletResponse response, Model model){
		if(projectId!=null){
			Pagination quoteDetail = enqQuoteService.getQuoteDetail(pageNo==null?1:pageNo, 5, projectId);
			model.addAttribute("projectId", projectId);
			model.addAttribute("quoteDetail", quoteDetail);
		}
	
		return "orgstructure/quoteDetailModel";
	}
	
	/**订单详情**/
	@RequireUser
	@RequestMapping("/loadOrderModel")
	@RequirePurchase
	@RequirePermission("branchManage")
	public String loadOrderModel(Integer pageNo,Integer projectId,HttpServletRequest request, HttpServletResponse response, Model model){
		if(projectId!=null){
			Pagination orderDetail =enqQuoteService.getOrderDetail(pageNo==null?1:pageNo, 5, projectId);
			model.addAttribute("projectId", projectId);
			model.addAttribute("orderDetail", orderDetail);
		}
		return "orgstructure/orderDetailModel";
	}
	
	
	                                                 /******角色管理模块******/
	                                      /*********显示除默认的角色之外的角色**********/
	
	/**角色管理列表**/
	@RequireUser
	@RequestMapping("/roleManage")
	@RequirePermission("roleManage")
	public String roleManage(Integer pageNo,HttpServletRequest request, HttpServletResponse response, Model model){
		Company company = ContextUtil.getCompany();
		Integer roleType=ContextUtil.getCurrentRoleType();
			 //分页
			 Pagination notDefaultRolesPage=userPermissionService.searchNotDefaultRoles(pageNo==null?1:pageNo, 10, company.getId(), roleType);
			 if(notDefaultRolesPage!=null && notDefaultRolesPage.getList()!=null && notDefaultRolesPage.getList().size()>0){
				 model.addAttribute("notDefaultRolesPage", notDefaultRolesPage);
				 return "orgstructure/rolesList";
			 }else{
				 return "orgstructure/firstAddRole";
			 }
			
	}
	
	/** 
	 * @Title: checkrolename 
	 * @Description: 验证角色名称是否重复
	 * @param rolename
	 * @return: JSONObject
	 * @author: 查恒 2016年11月14日 上午10:12:59 
	 */
	@ResponseBody
	@RequestMapping("/checkrolename")
	public JSONObject checkrolename(String rolename,Integer roleId,HttpServletRequest request, HttpServletResponse response){ Company company = ContextUtil.getCompany();
	JSONObject json =new JSONObject();	
	if(StringUtils.isNotBlank(rolename)){
			Map parameter=new HashMap();
			parameter.put("roleType", ContextUtil.getCurrentRoleType());
			parameter.put("companyId", company.getId());
			parameter.put("name", rolename);
			parameter.put("removed", 0);
			List<Role> roleByParameter = userPermissionService.getRoleByParameter(parameter);
			if(roleByParameter!=null && roleByParameter.size()>0){
				if(roleId!=null && roleByParameter.size()==1){
					if(!roleId.equals(roleByParameter.get(0).getId())){//编辑
						json.put("error", "该角色名称已存在！");
						return json;
					}
				}else{//新增
					json.put("error", "该角色名称已存在！");
					return json;
				}
			}
		}
		return json;
	}
	
	
	/**添加角色**/
	@RequireUser
	@RequestMapping("/addrole")
	@RequirePermission("roleManage")
	public String addRole(Integer roleId,String isdefault,HttpServletRequest request, HttpServletResponse response, Model model){
		
		Role currentRole = ContextUtil.getCurrentRole();
		
		//获得默认采购商的角色名称
		Map parameter=new HashMap();
		parameter.put("ifDefault", 1);
		parameter.put("roleType", currentRole.getRoleType());//目前没有供应商的添加角色
		parameter.put("removed", 0);
		List<Role> defaultRole = userPermissionService.getRoleByParameter(parameter);
		
		List<UserFunction> parentTree=functionService.findFuncByRoleId(currentRole.getId().intValue(),UserFuncTypeEnum.MENU.getValue(),UserFuncShowTypeEnum.LEFT.getValue());//根据当前的ROLEID拿到权限菜单
		
		List<UserFunction> branchTree=null;
		//如果是编辑，则查询分公司的所拥有权限
		if(roleId!=null){
			Role roleById = userPermissionService.getRoleById(roleId);
			//权限  只加载左侧菜单
			branchTree = functionService.findFuncByRoleId(roleId, UserFuncTypeEnum.MENU.getValue(),UserFuncShowTypeEnum.LEFT.getValue());
				
			model.addAttribute("role",roleById);
		}
		
		List<UserFunction> markTree = functionService.markTree(parentTree,branchTree);
		
		model.addAttribute("loadMenuTree",markTree);
		model.addAttribute("defaultRole",defaultRole);
		model.addAttribute("isdefault",isdefault);
		return "orgstructure/addRole";
	}
	
	
	
	
	
	/**保存或编辑角色**/
	@ResponseBody
	@RequestMapping("/saverole")
	public AjaxJson saveRole(HttpServletRequest request, HttpServletResponse response, Model model){
		Company company = ContextUtil.getCompany();
		Role currentRole = ContextUtil.getCurrentRole();
		String data=request.getParameter("data");
		if(StringUtils.isNotBlank(data)){
			try {
				Map<String,Object> parseMap = JSON.parseObject(data, Map.class);
				String roleName = (String) parseMap.get("roleName");
				String roleId = (String) parseMap.get("roleId");
				String isdefault = (String) parseMap.get("isdefault");
				parseMap.put("RoleType", currentRole.getRoleType());
				
				Role role=null;
				if(StringUtils.isNotBlank(roleId) && "2".equals(isdefault)){//编辑
					role = userPermissionService.getRoleById(Integer.parseInt(roleId));
				}else{
					role =new Role();
				}
				
				if(role!=null){
					role.setName(roleName);
					role.setRoleType(currentRole.getRoleType());
					role.setIfDefault(0);
					role.setIfAdmin(0);
					role.setRemoved(0);
					userPermissionService.saveOrUpdateRoleAuthority(company, parseMap,role);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				return AjaxJson.error("角色保存失败。");
			}
	
		}else{
			return AjaxJson.error("抱歉，数据不能空！");
		}
	
		
		return AjaxJson.success();
	}
	
	/**验证角色是否可以删除**/
	//角色下面没有员工就可以删除
	@ResponseBody
	@RequestMapping("/checkrole")
	public AjaxJson checkDelRole(Integer roleId,HttpServletRequest request, HttpServletResponse response, Model model){
		Company company = ContextUtil.getCompany();
		 List<UserRole> userRoles = userPermissionService.getUserRolesByRoleId(roleId);
		 AjaxJson ajson=new AjaxJson();
		 //先判断有没有员工申请
		 List<UserApplyCompany> userApplyCompany = userService.getUserApplyCompanyByRoleId(company.getId(),roleId,0);
		 if(userApplyCompany!=null && userApplyCompany.size()>0){
			 ajson.setSuccess(false);
			 ajson.setMsg("有成员正在申请该角色！");
			 ajson.setObj(1);
			 return ajson;
		 }
		 if(userRoles!=null && userRoles.size()>0){
			 ajson.setSuccess(false);
			 ajson.setMsg("有成员的角色无法删除！");
			 ajson.setObj(2);
			 return ajson;
		 }else{
			 return AjaxJson.success();
		 }
	}
	
	@ResponseBody
	@RequestMapping("/delrole")
	public AjaxJson delRole(Integer roleId,HttpServletRequest request, HttpServletResponse response, Model model){
		 //删除角色和角色的权限
		 Role roleById = userPermissionService.getRoleById(roleId);
		 userPermissionService.deleteRole(roleById);
		 functionService.delAuthorityByRoleId(roleId);
		 return AjaxJson.success();
	}
	
	
}
